package com.skyable.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skyable.account.entity.SysRole;
import com.skyable.account.entity.SysRolePermission;
import com.skyable.account.service.IRolePermissionService;
import com.skyable.account.service.IRoleService;
import com.skyable.account.mapper.RoleMapper;
import com.skyable.common.common.ServiceResult;
import com.skyable.common.constants.exception.AccountExcpConstants;
import com.skyable.common.constants.param.CommonParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author GaoYuan
 * @title: RoleServiceImpl
 * @projectName spring-cloud-oauth2-demo
 * @description: TODO
 * @date 2021/4/1713:59
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper,SysRole> implements IRoleService {

    @Autowired
    private IRolePermissionService rolePermissionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult<SysRole> insertRole(SysRole sysRole, List<Long> permissionIdList) {
        ServiceResult<SysRole> serviceResult = new ServiceResult<>();
        SysRole role = lambdaQuery().eq(SysRole::getRoleCode, sysRole.getRoleCode()).one();
        if(role != null) {
            serviceResult.setError(AccountExcpConstants.ERROR_CODE_ROLE_EXISTS,AccountExcpConstants.ERROR_MSG_ROLE_EXISTS);
            return serviceResult;
        }
        sysRole.setStatus(0);
        sysRole.setDelFlag(0);
        baseMapper.insert(sysRole);

        if(permissionIdList != null && !permissionIdList.isEmpty()) {
            List<SysRolePermission> sysRolePermissionList = generateRolePermission(sysRole.getId(),permissionIdList);
            rolePermissionService.saveBatch(sysRolePermissionList);
        }
        serviceResult.setResult(sysRole);
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult<SysRole> updateRole(SysRole sysRole, List<Long> permissionIdList) {
        ServiceResult<SysRole> serviceResult = new ServiceResult<>();
        SysRole role = lambdaQuery().ne(SysRole::getId,sysRole.getId()).eq(SysRole::getRoleCode, sysRole.getRoleCode()).one();
        if(role != null) {
            serviceResult.setError(AccountExcpConstants.ERROR_CODE_ROLE_EXISTS,AccountExcpConstants.ERROR_MSG_ROLE_EXISTS);
            return serviceResult;
        }
        baseMapper.updateById(sysRole);

        if(permissionIdList != null && !permissionIdList.isEmpty()) {
            //删除之前的权限信息
            QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(CommonParams.DATA_BASE_ROLE_ID,sysRole.getId());
            rolePermissionService.remove(queryWrapper);
            //保存新权限信息
            List<SysRolePermission> sysRolePermissionList = generateRolePermission(sysRole.getId(),permissionIdList);
            rolePermissionService.saveBatch(sysRolePermissionList);
        }

        serviceResult.setResult(sysRole);
        return serviceResult;
    }

    @Override
    public ServiceResult<IPage<SysRole>> findRoleListByPage(int page, int limit, SysRole sysRole) {
        ServiceResult<IPage<SysRole>> serviceResult = new ServiceResult<>();
        Page<SysRole> sysRolePage = new Page<>(page, limit);
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        //查询未停用的角色
        sysRole.setStatus(0);
        queryWrapper.setEntity(sysRole);
        IPage<SysRole> roleIPage = baseMapper.selectPage(sysRolePage, queryWrapper);
        serviceResult.setResult(roleIPage);
        return serviceResult;
    }

    @Override
    public ServiceResult<List<SysRole>> findRoleList() {
        ServiceResult<List<SysRole>> serviceResult = new ServiceResult<>();
        List<SysRole> sysRoleList = lambdaQuery().eq(SysRole::getStatus,0).list();
        serviceResult.setResult(sysRoleList);
        return serviceResult;
    }

    @Override
    public ServiceResult<SysRole> findRoleById(Long roleId) {
        ServiceResult<SysRole> serviceResult = new ServiceResult<>();
        SysRole sysRole = lambdaQuery().eq(SysRole::getId, roleId).one();

        //查询角色权限集合
        List<SysRolePermission> sysRolePermissionList = rolePermissionService.lambdaQuery().eq(SysRolePermission::getRoleId, roleId).list();
        if(sysRolePermissionList != null && !sysRolePermissionList.isEmpty()) {
            List<Long> permissionIdList = sysRolePermissionList.stream().map(SysRolePermission::getPermissionId).collect(Collectors.toList());
            sysRole.setPermissionIdList(permissionIdList);
        }

        serviceResult.setResult(sysRole);
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult<Integer> deleteRoleById(Long roleId) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();
        //删除角色权限信息
        QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CommonParams.DATA_BASE_ROLE_ID,roleId);
        rolePermissionService.remove(queryWrapper);
        //删除角色
        int result = baseMapper.deleteById(roleId);
        serviceResult.setResult(result);
        return serviceResult;
    }

    private List<SysRolePermission> generateRolePermission(Long roleId, List<Long> permissionIdList) {
        List<SysRolePermission> sysRolePermissionList = permissionIdList.stream().map(permissionId -> {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setPermissionId(permissionId);
            sysRolePermission.setRoleId(roleId);
            return sysRolePermission;
        }).collect(Collectors.toList());
        return sysRolePermissionList;
    }
}
